package com.train.chatspring.controller;

import com.train.chatspring.model.ChatMessage;
import com.train.chatspring.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// 新增WebSocket消息处理器
@RestController
@RequestMapping("/app")
@RequiredArgsConstructor
@Slf4j
public class ChatWebSocketHandler {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private UserService userService;

    @MessageMapping("/sendMessage")
    public void handleMessage(@Payload ChatMessage message) {
        System.out.println("Received message: " + message); // 确认是否进入方法
        String senderId = message.getSenderId();
        String receiverId = message.getReceiverId();

        // 打印发送者和接收者ID
        System.out.println("Sending message from: " + senderId + " to: " + receiverId);

        // 验证发送者和接收者是否为好友
        if (!userService.areFriends(senderId, receiverId)) {
            throw new RuntimeException("对方不是你的好友，无法发送消息");
        }

        // 打印消息内容
        System.out.println("Message content: " + message.getText());

        // 广播消息到指定接收者
        String broadcastDestination = "/user/" + receiverId + "/messages";
        System.out.println("Broadcasting message to: " + broadcastDestination);
        messagingTemplate.convertAndSendToUser(receiverId, "/messages", message);
    }
}
